<template>
  <div class="form-fragment">
    <div class="form-container">
      <tbc-dynamic-form :form="dynamicForm" class="compact"/>

      <tbc-dynamic-table :data="dataList" :cols="cols" border>
        <template #empty>
          <el-button type="text" icon="el-icon-plus" @click="onButtonClick('', 'add', -1)">添加一行</el-button>
        </template>
      </tbc-dynamic-table>
    </div>
  </div>
</template>
<script lang="ts">
import {defineComponent, reactive, toRefs} from 'vue'

export default defineComponent({

  setup() {
    const onButtonClick = (data: string, code: string, index: number) => {
      if (code === 'add') {
        let dataItem: Record<string, string> = JSON.parse(JSON.stringify(state.dataItem))
        dataItem = propsFormat(dataItem)
        return (state.dataList as Record<string, string>[]).push(dataItem)
      }
      if (code === 'delete' && state.dataList.length) {
        return state.dataList.splice(index, 1)
      }
    }
    const state = reactive({
      dynamicForm: [
        {label: '市场价', type: 'input-number', field: 'market_price', value: 0, remark: ''},
        {label: '销售价', type: 'input-number', field: 'shop_price', value: 0, remark: '(如果添加多规格则无效)'},
        {label: '库存', type: 'input-number', field: 'stock', value: 0, remark: '(如果添加多规格则无效)'},
      ],
      fillForm: {skuPrice: '', skuStock: '', skuOuterId: '', skuBarcode: ''},
      attr: [],
      imgElement: null,
      cols: [],
      baseCols: [
        {label: '售价', prop: 'skuPrice', type: 'input-number', width: 140, class: 'border'},
        {label: '库存', prop: 'skuStock', type: 'input-number', width: 140, class: 'border'},
        {label: '商家编码', prop: 'skuOuterId', type: 'input', width: 140, class: 'border'},
        {label: '商品条形码', prop: 'skuBarcode', type: 'input', width: 140, class: 'border'},
        {
          label: '操作', prop: 'action', type: 'action', width: 160, click:
          onButtonClick,
          button: [
            {code: 'add', type: 'primary', label: '添加'},
            {code: 'delete', type: 'danger', label: '删除'}
          ]
        }],
      dataItem: {skuPrice: '', skuStock: '', skuOuterId: '', skuBarcode: ''},
      dataList: [],
      index: -1
    })
    const init = (data) => {
      const specList: { [k: string]: any }[] = data.goods_spec || []
      const dataList: Record<string, string | number>[] = []
      specList.forEach(item => {
        const dataItem: Record<string, string | number> = {}
        dataItem.skuPrice = parseFloat(item.skuPrice)
        dataItem.skuStock = item.skuStock
        dataItem.skuBarcode = item.skuBarcode
        dataItem.skuOuterId = item.skuOuterId
        dataItem.props = item.props
        item.props.forEach((prop: Record<string, string>) => dataItem[prop.attr_id] = prop.label)
        dataList.push(dataItem)
      });
      (state.dataList as Record<string, string| number>[]) = dataList
    }

    // 设置规格属性
    const setAttributeList = (attrList) => {
      const cols: Record<string, string>[] = []
      attrList.forEach(item => {
        state.dataItem[item.attr_id] = ''
        cols.push({
          label: item.attr_name,
          prop: item.attr_id.toString(),
          type: 'input',
          class: 'border'
        })
      });
      (state.cols as Record<string, string>[]) = [...cols, ...state.baseCols] as Record<string, string>[]
      if (!state.dataList.length && onButtonClick) onButtonClick('', 'add', 0)
    }

    const propsFormat = (data) => {
      const props: Record<string, string>[] = []
      for (let key in data) {
        if (key.indexOf('sku') === -1) {
          props.push({
            attr_id: key,
            value: '',
            label: '',
            remark: '',
            ext_id: ''
          })
        }
      }
      data.props = props
      return data
    }

    const detectProps = (dataList) => {
      dataList.forEach(item => {
        item.props.forEach(prop => {
          if (prop.value === '' && typeof item[prop.attr_id] !== 'undefined') {
            prop.value = item[prop.attr_id];
          }
          if (prop.label === '') prop.label = prop.value;
        })
      })
      return dataList
    }
    const getFormData = () => {
      const form: Record<string, any> = {}
      state.dynamicForm.forEach(item => form[item.field] = item.value)
      let dataList = detectProps(JSON.parse(JSON.stringify(state.dataList)))
      console.log(dataList)
      form.goods_spec = JSON.stringify(dataList)
      return form
    }

    return {
      ...toRefs(state),
      init,
      onButtonClick,
      setAttributeList,
      getFormData
    }
  }
})
</script>